/*
 * Copyright 2012 Jonathan St-Michel <jonathan@abiwebz.net>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.abiwebz.office.rm.mysql.driver.panel;

import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.DefaultComboBoxModel;
import net.abiwebz.office.rm.database.DatabaseDriver;
import net.abiwebz.office.rm.database.configuration.DriverConfigurationPanel;

/**
 *
 * @author Jonathan St-Michel <jonathan@abiwebz.net>
 */
public class MySQLDriverConfigurationPanel extends DriverConfigurationPanel {

    /**
     * Creates new form MySQLDriverConfigurationPanel
     */
    public MySQLDriverConfigurationPanel(DatabaseDriver driver) {
        super(driver);
        initComponents();
        // Register DocumentListeners if not a DocumentListener implement any
        // listener and user fire(null);
        tfHostname.getDocument().addDocumentListener(this);
        tfPort.getDocument().addDocumentListener(this);

    }

    public String getHostname() {
        return tfHostname.getText();
    }

    public String getPort() {
        return tfPort.getText();
    }

    public String getDatabase() {
        return (String) cbDatabases.getSelectedItem();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lHostname = new javax.swing.JLabel();
        tfHostname = new javax.swing.JTextField();
        tfPort = new javax.swing.JTextField();
        lPort = new javax.swing.JLabel();
        lUsername = new javax.swing.JLabel();
        tfUsername = new javax.swing.JTextField();
        lPassword = new javax.swing.JLabel();
        pfPassword = new javax.swing.JPasswordField();
        lVerify = new javax.swing.JLabel();
        pfVerification = new javax.swing.JPasswordField();
        lDatabase = new javax.swing.JLabel();
        cbDatabases = new javax.swing.JComboBox<String>();
        bReload = new javax.swing.JButton();

        lHostname.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.lHostname.text")); // NOI18N

        tfHostname.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.tfHostname.text")); // NOI18N

        tfPort.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.tfPort.text")); // NOI18N

        lPort.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.lPort.text")); // NOI18N

        lUsername.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.lUsername.text")); // NOI18N

        tfUsername.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.tfUsername.text")); // NOI18N

        lPassword.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.lPassword.text")); // NOI18N

        pfPassword.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.pfPassword.text")); // NOI18N

        lVerify.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.lVerify.text")); // NOI18N

        pfVerification.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.pfVerification.text")); // NOI18N

        lDatabase.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.lDatabase.text")); // NOI18N

        cbDatabases.setEditable(true);
        cbDatabases.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbDatabasesItemStateChanged(evt);
            }
        });

        bReload.setText(org.openide.util.NbBundle.getMessage(MySQLDriverConfigurationPanel.class, "MySQLDriverConfigurationPanel.bReload.text")); // NOI18N
        bReload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bReloadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lHostname)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfHostname, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lPort)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lUsername)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfUsername))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pfPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lVerify)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pfVerification))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lDatabase)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbDatabases, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bReload)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lDatabase, lHostname, lPassword, lUsername});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lHostname)
                    .addComponent(tfHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lPort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lUsername)
                    .addComponent(tfUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lPassword)
                    .addComponent(pfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lVerify)
                    .addComponent(pfVerification, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lDatabase)
                    .addComponent(cbDatabases, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bReload))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bReloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReloadActionPerformed
        try {
            Connection c = this.driverInstance.createConnection(tfHostname.getText(), "", tfPort.getText(), tfUsername.getText(), pfPassword.getPassword());
            cbDatabases.setModel(new DefaultComboBoxModel<String>(this.driverInstance.getDatabases(c)));
            fire(null);
        } catch (SQLException ex) {
            //System.out.println("invalid Connection");
        }
    }//GEN-LAST:event_bReloadActionPerformed

    private void cbDatabasesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbDatabasesItemStateChanged
        fire(null);
    }//GEN-LAST:event_cbDatabasesItemStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bReload;
    private javax.swing.JComboBox<String> cbDatabases;
    private javax.swing.JLabel lDatabase;
    private javax.swing.JLabel lHostname;
    private javax.swing.JLabel lPassword;
    private javax.swing.JLabel lPort;
    private javax.swing.JLabel lUsername;
    private javax.swing.JLabel lVerify;
    private javax.swing.JPasswordField pfPassword;
    private javax.swing.JPasswordField pfVerification;
    private javax.swing.JTextField tfHostname;
    private javax.swing.JTextField tfPort;
    private javax.swing.JTextField tfUsername;
    // End of variables declaration//GEN-END:variables

    @Override
    public boolean check() {
        if (getHostname().equals("")) {
            this.message = "Hostname must have a value entered !";
            return false;
        }

        if (!getPort().equals("")) { // Verify if port is valid number
            try {
                int i = Integer.parseInt(getPort());
                if (i < 0) {
                    this.message = "Port number is invalid !";
                    return false;
                }
            } catch (NumberFormatException ex) {
                this.message = "Port number is invalid !";
                return false;
            }
        }
        
        if (getDatabase() == null) {
            this.message = "No database is selected !";
            return false;
        }


        this.message = "";
        return true;
    }

    @Override
    public String getJDBCUrl() {
        return this.driverInstance.buildURL(getHostname(), getDatabase(), getPort());
    }
}
